﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZ;
using DAL;

namespace SinhNhat
{
    public partial class Category : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Guid categoryID = new Guid(hdID.Value);
                CategoryBIZ categoryBIZ = new CategoryBIZ();
                ProductBIZ productBIZ = new ProductBIZ();

                var category = categoryBIZ.GetByID(categoryID);
                headerTitle.InnerText = lblTitle.Text = category.CategoryName;

                List<CATEGORY> listChild = categoryBIZ.GetChildNode(categoryID.ToString());
                List<PRODUCT> list = new List<PRODUCT>();

                list.AddRange(productBIZ.GetByCategoryForUser(categoryID));

                for (int i = 0; i < listChild.Count; i++)
                {
                    list.AddRange(productBIZ.GetByCategoryForUser(listChild[i].CategoryID));
                }

                CollectionPager1.DataSource = list;
                CollectionPager1.BindToControl = rptProduct;
                rptProduct.DataSource = CollectionPager1.DataSourcePaged;
                rptProduct.DataBind();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            rptProduct.ItemCommand += new RepeaterCommandEventHandler(rptProduct_ItemCommand);
        }

        void rptProduct_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandArgument.Equals("Add"))
            {
                Dictionary<string, CartObject> listCart = null;
                if (Session[SinhNhat.Properties.Resources.CookieName] == null)
                {
                    listCart = new Dictionary<string, CartObject>();
                }
                else
                {
                    listCart = (Dictionary<string, CartObject>)Session[SinhNhat.Properties.Resources.CookieName];
                }

                CartObject cartObject = null;
                if (listCart.ContainsKey(e.CommandName))
                {
                    listCart[e.CommandName].Quantity += 1;
                }
                else
                {
                    cartObject = new CartObject(new PRODUCT() { ProductID = WebUtils.ToGuid(e.CommandName) }, 1);
                    listCart.Add(e.CommandName, cartObject);
                }

                Session[SinhNhat.Properties.Resources.CookieName] = listCart;

                Response.Redirect("/Cart.aspx");
            }
        }
    }
}